<?php

namespace App\Http\Requests\Admin;

use App\Models\Admin;
use Illuminate\Foundation\Http\FormRequest;
use Illuminate\Validation\Rule;

class AdminStoreRequest extends FormRequest
{
    /**
     * Get the validation rules that apply to the request.
     *
     * @return array
     */
    public function rules(): array
    {
        switch ($this->method()) {
            case "POST":
                return [
                    'username' => 'bail|required|string|unique:admins,username',
                    'password' => 'bail|required|string',
                    'role' => 'bail|required|in:admin,temp',
                    'status' => 'bail|nullable|in:1,2',
                ];
            case "PUT":
                return [
                    'username' => ['bail', 'required', 'string', function($attribute, $value, $fail) {
                        $admin = Admin::where('username', request('username'))->first();
                        if ($admin && $admin->id !== request('id')) {
                            return $fail('用户名已存在');
                        }

                    }],
                    'password' => 'bail|nullable|string',
                    'role' => 'bail|required|in:admin,temp',
                    'status' => 'bail|nullable|in:1,2',
                ];
            default:
                return [];
        }
    }
}
